********************************************************************************
* analyze_main.do
* Purpose: Produce main firm-level DiD event-study results (Table 2, Figure 2,
*          Table B6, Figure B6).
*
* Table 2   : DiD estimates for impact of M&As on firm outcomes.
*             Outcomes: log(Employment), log(Average Payrolls), Profit Margins,
*             Return on Assets. Column structure:
*               Col 1: Target firms (acquisitions)
*               Col 2: Acquirer firms (acquisitions)
*               Col 3: Aggregate (targets + acquirers pooled, acquisitions)
*               Col 4: Aggregate (targets + acquirers pooled, mergers)
*             Input : $data/firm_matched.dta
*             Output: $out/table2.csv
*
* Figure 2  : Event-study plots corresponding to Table 2.
*             Panels A-D: Acquirer vs. Target for acquisitions
*               A: log(Employment), B: log(Average Payrolls),
*               C: Profit Margins,  D: Return on Assets
*             Panels E-H: Acquisition vs. Merger (aggregate)
*               E: log(Employment), F: log(Average Payrolls),
*               G: Profit Margins,  H: Return on Assets
*             Input : $data/firm_matched.dta
*             Output: $out/Figure2_A.pdf ... $out/Figure2_H.pdf
*
* Table B6  : DiD estimates for additional firm outcomes (Appendix B.6).
*             Outcomes: log(Revenue), NIBTEI per Worker, log(Markups),
*             Realized Capital Gains. Same 4-column structure as Table 2.
*             Note: Realized Capital Gains require merging in owner-level data.
*             Input : $data/firm_matched.dta, $data/firm_owner.dta
*             Output: $out/tableB6.csv, $out/FigureB6_1.csv ... $out/FigureB6_4.csv
*
* Figure B6 : Event-study plots corresponding to Table B6.
*             Panels A-D: Acquirer vs. Target for acquisitions
*               A: log(Revenue), B: NIBTEI per Worker,
*               C: log(Markups),  D: Realized Capital Gains
*             Panels E-H: Acquisition vs. Merger (aggregate)
*               E: log(Revenue), F: NIBTEI per Worker,
*               G: log(Markups),  H: Realized Capital Gains
*             Input : $data/firm_matched.dta, $data/firm_owner.dta
*             Output: $out/FigureB6_A.pdf ... $out/FigureB6_H.pdf
*
* Regression specification:
*   FE: id + event-time x 2-digit NAICS (i.t##i.naics)
*   Controls: quartic polynomial in firm age (age*)
*   Standard errors clustered at the firm level.
*   Outcomes winsorized at the 5th/95th percentile by year.
*   Average post-event impact = average of ds_7 through ds_12 (years 0 to 5).
********************************************************************************
*        Firm Analysis        *
********************************************************************************
set more off

********************************************************************************
							* Table 2 *
********************************************************************************
use $data/firm_matched, clear

**  Dependent Variables ***
gen y_revenue 		= log(total_revenue)
gen y_emp		 	= log(PD7_AvgEmp_NonZero)
gen y_avg_payroll 	= log(avg_payroll)
gen y_markup	 	= log(theta_ct*(sales_goods_and_services/total_cost_of_sales))
gen y_ebit_lbr		= (net_income_befor_taxextraitems )/PD7_AvgEmp_NonZero
gen y_netprof		= (total_revenue - total_expense)/total_revenue
gen y_roa 			= (total_revenue - total_expense)/total_assets

label var y_revenue 		"log(Revenue)"
label var y_emp 			"log(Employment)"
label var y_avg_payroll 	"log(Average Payrolls)"
label var y_markup 			"log(Markups)"
label var y_ebit_lbr		"NIBTEI per worker"
label var y_netprof 		"Profit Margins"
label var y_roa				"Return on Assets"

global FE				"id i.t##i.naics"
global clusters			"firm_id"
global ind_var 			"treated##ds_*"
global average_impact 	"(1.treated#1.ds_7 + 1.treated#1.ds_8 + 1.treated#1.ds_9 + 1.treated#1.ds_10 + 1.treated#1.ds_11 + 1.treated#1.ds_12)/6"

**# Table 2 - Column 1
preserve
gstats winsor y_*, replace cuts(5 95)  by(year)

* sample selection
keep if matched_deal_type == 0
keep if matched_acq == 0

local varlist "emp avg_payroll netprof roa"
foreach v in `varlist'{
	eststo es1_`v': reghdfe y_`v' $ind_var age*, a($FE) vce( cluster $clusters ) tol(1e-6)

	eststo m1_`v': lincomest $average_impact
	
	estimate restore es1_`v'
	summ `e(depvar)' if treated == 1 & t == -1
	estadd scalar ym = `r(mean)'  
	estimates restore es1_`v'
}


**# Table 2 - Column 2
restore, preserve
gstats winsor y_*, replace cuts(5 95)  by(year)

* sample selection
keep if matched_deal_type == 0
keep if matched_acq == 1

local varlist "emp avg_payroll netprof roa"
foreach v in `varlist'{
	eststo es2_`v': reghdfe y_`v' $ind_var age*, a($FE) vce( cluster $clusters ) tol(1e-6)

	eststo m2_`v': lincomest $average_impact
	
	estimate restore es2_`v'
	summ `e(depvar)' if treated == 1 & t == -1
	estadd scalar ym = `r(mean)'  
	estimates restore es2_`v'
}


**# Figure 2 - A
#delimit ;
make_eventstudy emp,
	models("es2_emp es1_emp")
	colors("dknavy dkorange")
	labels("Acquirer Target")
	fmt("%9.1fc") ylab("-0.4(0.1)0.4")
	fig("Figure2") subfig("A");

#delimit cr

**# Figure 2 - B
#delimit ;
make_eventstudy avg_payroll,
	models("es2_avg_payroll es1_avg_payroll")
	colors("dknavy dkorange")
	labels("Acquirer Target")
	fmt("%9.2fc") ylab("-0.1(0.05)0.1")
	fig("Figure2") subfig("B");

#delimit cr

**# Figure 2 - C
#delimit ;
make_eventstudy netprof,
	models("es2_netprof es1_netprof")
	colors("dknavy dkorange")
	labels("Acquirer Target")
	fmt("%9.2fc") ylab("-0.08(0.02)0.06")
	fig("Figure2") subfig("C");

#delimit cr

**# Figure 2 - D
#delimit ;
make_eventstudy roa,
	models("es2_roa es1_roa")
	colors("dknavy dkorange")
	labels("Acquirer Target")
	fmt("%9.2fc") ylab("-0.08(0.02)0.04")
	fig("Figure2") subfig("D");

#delimit cr

**# Table 2 - Column 3
restore, preserve
gstats winsor y_*, replace cuts(5 95)  by(year)

* sample selection
keep if matched_deal_type == 0

local varlist "emp avg_payroll netprof roa"
foreach v in `varlist'{
	eststo es3_`v': reghdfe y_`v' $ind_var age*, a($FE) vce( cluster $clusters ) tol(1e-6)

	eststo m3_`v': lincomest $average_impact
	
	estimate restore es3_`v'
	summ `e(depvar)' if treated == 1 & t == -1
	estadd scalar ym = `r(mean)'  
	estimates restore es3_`v'
}

**# Table 2 - Column 4
restore, preserve
gstats winsor y_*, replace cuts(5 95)  by(year)

* sample selection
keep if matched_deal_type == 1

local varlist "emp avg_payroll netprof roa"
foreach v in `varlist'{
	eststo es4_`v': reghdfe y_`v' $ind_var age*, a($FE) vce( cluster $clusters ) tol(1e-6)

	eststo m4_`v': lincomest $average_impact
	
	estimate restore es4_`v'
	summ `e(depvar)' if treated == 1 & t == -1
	estadd scalar ym = `r(mean)'
	estimates restore es4_`v'
}

#delimit ;
local first = 1;
local varlist "emp avg_payroll netprof roa";

foreach v in `varlist'{;
	if `first'{;
		local replace_append "replace";
		local title "f collabels(none) noobs title("") mtitle("Target" "Acquirer" "Acquisition" "Merger") coeflabel((1) "`:variable label y_`v''")";
		local first = 0;
	};
	else  {;
		local replace_append "append";
		local title "plain f collabels(none) noobs title("") nomtitles coeflabel((1) "`:variable label y_`v''")";
	};

	esttab m*_`v' using "$out/table2.csv", 
	`replace_append' `title'
	starlevel(* 0.10 ** 0.05 *** 0.01) 
	cells( b(star fmt(3)) se(par fmt(3)) ) type
	label;
	
	esttab es*_`v' using "$out/table2.csv", 
	append plain f collabels(none) keep("") nomtitles 
	stats(ym r2_a N, fmt(%9.2f %9.3f %9.0fc) label("Mean at t=-1" "Adj. R squared" "Firm-Year Obs.")) type;
};

#delimit cr


**# Figure 2 - E
#delimit ;
make_eventstudy emp,
	models("es3_emp es4_emp")
	colors("red black")
	labels("Acquisition Merger")
	fmt("%9.1fc") ylab("-0.4(0.1)0.4")
	fig("Figure2") subfig("E");

#delimit cr

**# Figure 2 - F
#delimit ;
make_eventstudy avg_payroll,
	models("es3_avg_payroll es4_avg_payroll")
	colors("red black")
	labels("Acquisition Merger")
	fmt("%9.2fc") ylab("-0.1(0.05)0.1")
	fig("Figure2") subfig("F");

#delimit cr

**# Figure 2 - G
#delimit ;
make_eventstudy netprof,
	models("es3_netprof es4_netprof")
	colors("red black")
	labels("Acquisition Merger")
	fmt("%9.2fc") ylab("-0.08(0.02)0.06")
	fig("Figure2") subfig("G");

#delimit cr

**# Figure 2 - H
#delimit ;
make_eventstudy roa,
	models("es3_roa es4_roa")
	colors("red black")
	labels("Acquisition Merger")
	fmt("%9.2fc") ylab("-0.08(0.02)0.04")
	fig("Figure2") subfig("H");

#delimit cr

restore, not
estimates clear

********************************************************************************
							* Table B6 *
********************************************************************************
use $data/firm_matched, clear

merge 1:1 entid_syn year_prior year using $data/firm_owner, keep(1 3) nogen

**  Dependent Variables ***
gen y_revenue 		= log(total_revenue)
gen y_ebit_lbr		= (net_income_befor_taxextraitems )/PD7_AvgEmp_NonZero
gen y_markup	 	= log(theta_ct*(sales_goods_and_services/total_cost_of_sales))
gen y_g				= cap_tot_net_calc

label var y_revenue 		"log(Revenue)"
label var y_ebit_lbr		"NIBTEI per Worker"
label var y_markup 			"log(Markups)"
label var y_g 				"Realized Capital Gains"

global FE				"id i.t##i.naics"
global clusters			"firm_id"
global ind_var 			"treated##ds_*"
global average_impact 	"(1.treated#1.ds_7 + 1.treated#1.ds_8 + 1.treated#1.ds_9 + 1.treated#1.ds_10 + 1.treated#1.ds_11 + 1.treated#1.ds_12)/6"

**# Table B6 - Column 1
preserve
gstats winsor y_*, replace cuts(5 95)  by(year)

* sample selection
keep if matched_deal_type == 0
keep if matched_acq == 0

local varlist "revenue ebit_lbr markup g"
foreach v in `varlist'{
	eststo es1_`v': reghdfe y_`v' $ind_var age*, a($FE) vce( cluster $clusters ) tol(1e-6)

	eststo m1_`v': lincomest $average_impact
	
	estimate restore es1_`v'
	summ `e(depvar)' if treated == 1 & t == -1
	estadd scalar ym = `r(mean)'  
	estimates restore es1_`v'
}

**# Table B6 - Column 2
restore, preserve
gstats winsor y_*, replace cuts(5 95)  by(year)

* sample selection
keep if matched_deal_type == 0
keep if matched_acq == 1

local varlist "revenue ebit_lbr markup g"
foreach v in `varlist'{
	eststo es2_`v': reghdfe y_`v' $ind_var age*, a($FE) vce( cluster $clusters ) tol(1e-6)

	eststo m2_`v': lincomest $average_impact
	
	estimate restore es2_`v'
	summ `e(depvar)' if treated == 1 & t == -1
	estadd scalar ym = `r(mean)'  
	estimates restore es2_`v'
}

**# Figure B6 - A
#delimit ;
make_eventstudy revenue,
	models("es2_revenue es1_revenue")
	colors("dknavy dkorange")
	labels("Acquirer Target")
	fmt("%9.1fc") ylab("-0.8(0.2)0.6")
	fig("FigureB6") subfig("A");

#delimit cr

**# Figure B6 - B
#delimit ;
make_eventstudy ebit_lbr,
	models("es2_ebit_lbr es1_ebit_lbr")
	colors("dknavy dkorange")
	labels("Acquirer Target")
	fmt("%9.0fc") ylab("-20e3(10e3)20e3")
	fig("FigureB6") subfig("B");

#delimit cr

**# Figure B6 - C
#delimit ;
make_eventstudy markup,
	models("es2_markup es1_markup")
	colors("dknavy dkorange")
	labels("Acquirer Target")
	fmt("%9.2fc") ylab("-0.2(0.1)0.2")
	fig("FigureB6") subfig("C");

#delimit cr

**# Figure B6 - D
#delimit ;
make_eventstudy g,
	models("es2_g es1_g")
	colors("dknavy dkorange")
	labels("Acquirer Target")
	fmt("%9.0fc") ylab("-100e3(50e3)150e3")
	fig("FigureB6") subfig("D");

#delimit cr

**# Table B6 - Column 3
restore, preserve
gstats winsor y_*, replace cuts(5 95)  by(year)

* sample selection
keep if matched_deal_type == 0

local varlist "revenue ebit_lbr markup g"
foreach v in `varlist'{
	eststo es3_`v': reghdfe y_`v' $ind_var age*, a($FE) vce( cluster $clusters ) tol(1e-6)

	eststo m3_`v': lincomest $average_impact
	
	estimate restore es3_`v'
	summ `e(depvar)' if treated == 1 & t == -1
	estadd scalar ym = `r(mean)'  
	estimates restore es3_`v'
}

**# Table B6 - Column 4
restore, preserve
gstats winsor y_*, replace cuts(5 95)  by(year)

* sample selection
keep if matched_deal_type == 1

local varlist "revenue ebit_lbr markup g"
foreach v in `varlist'{
	eststo es4_`v': reghdfe y_`v' $ind_var age*, a($FE) vce( cluster $clusters ) tol(1e-6)

	eststo m4_`v': lincomest $average_impact
	
	estimate restore es4_`v'
	summ `e(depvar)' if treated == 1 & t == -1
	estadd scalar ym = `r(mean)'  
	estimates restore es4_`v'
}

#delimit ;
local first = 1;

local varlist "revenue ebit_lbr markup g";
foreach v in `varlist'{;
	if `first'{;
		local replace_append "replace";
		local title "f collabels(none) noobs title("") mtitle("Target" "Acquirer" "Acquisition" "Merger") coeflabel((1) "`:variable label y_`v''")";
		local first = 0;
	};
	else  {;
		local replace_append "append";
		local title "plain f collabels(none) noobs title("") nomtitles coeflabel((1) "`:variable label y_`v''")";
	};

	esttab m*_`v' using "$out/tableB6.csv", 
	`replace_append' `title'
	starlevel(* 0.10 ** 0.05 *** 0.01) 
	cells( b(star fmt(3)) se(par fmt(3)) ) type
	label;
	
	esttab es*_`v' using "$out/tableB6.csv", 
	append plain f collabels(none) keep("") nomtitles 
	stats(ym r2_a N, fmt(%9.2f %9.3f %9.0fc) label("Mean at t=-1" "Adj. R squared" "Firm-Year Obs.")) type;
};

#delimit cr

**# Figure B6 - E
#delimit ;
make_eventstudy revenue,
	models("es3_revenue es4_revenue")
	colors("red black")
	labels("Acquisition Merger")
	fmt("%9.1fc") ylab("-0.8(0.2)0.6")
	fig("FigureB6") subfig("E");

#delimit cr

**# Figure B6 - F
#delimit ;
make_eventstudy ebit_lbr,
	models("es3_ebit_lbr es4_ebit_lbr")
	colors("red black")
	labels("Acquisition Merger")
	fmt("%9.0fc") ylab("-20e3(10e3)20e3")
	fig("FigureB6") subfig("F");

#delimit cr

**# Figure B6 - G
#delimit ;
make_eventstudy markup,
	models("es3_markup es4_markup")
	colors("red black")
	labels("Acquisition Merger")
	fmt("%9.2fc") ylab("-0.2(0.1)0.2")
	fig("FigureB6") subfig("G");

#delimit cr

**# Figure B6 - H
#delimit ;
make_eventstudy g,
	models("es3_g es4_g")
	colors("red black")
	labels("Acquisition Merger")
	fmt("%9.0fc") ylab("-100e3(50e3)150e3")
	fig("FigureB6") subfig("H");
#delimit cr